<?php

namespace app\admin\logic;

use app\common\logic\BaseLogic;
use app\common\model\mysql\OrderModel;
use app\common\model\mysql\UserIntegralLogModel;
use app\common\model\mysql\UserLevelModel;
use app\common\model\mysql\UserModel;
use think\facade\Db;


class OrderLogic extends BaseLogic
{
    public function index($request)
    {
        $search = $request->param();
        $where = [];
        if (!empty($search['nickname'])) {
            $where[] = ['b.nickname', 'like', "%{$search['nickname']}%"];
        }

        if (!empty($search['name'])) {
            $where[] = ['c.name', 'LIKE', "%{$search['name']}%"];
        }

        empty($search['order_status']) ? $search['order_status'] = '' : $search['order_status'];
        if (!empty($search['order_status'])) {
            $where[] = ['a.order_status', '=', $search['order_status']];
        }
        if ($request->account['project_ids']) {
            $where[] = ['a.project_id', 'in', $request->account['project_ids']];
        }


        $list = Db::table('pro_order')->alias('a')->join('pro_user b', 'a.user_id = b.id')->join('pro_project c', 'c.id = a.project_id')->where($where)->field('a.id,a.order_sn,a.order_integral,a.add_integral,a.client_name,a.client_mobile,a.client_realname,a.client_address,a.create_time,a.order_status,b.nickname,c.name')->order(['a.id' => 'DESC'])->paginate(['list_rows' => 20, "query" => $search], false);
        //转换成数据对象
        $data = $list->items();
        foreach ($data as &$value) {
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
        }

        return view('Order/order', compact('list', 'search', 'data'));
    }

    public function read($request, $id)
    {
        $info = OrderModel::getOne(['id' => $id]);

        return view('Order/order_detail', compact('info'));
    }


    /**
     * @param $request
     * @return \think\Response
     */
    public function orderOperate($request)
    {
        $post = $request->post();

        $order = OrderModel::getOne(['id' => $post['order_id']]);

        if (!$order) return $this->responseError('订单不存在');

        if ($order['order_status'] == 3) return $this->responseError('订单已完成，无法进行操作');

        Db::startTrans();
        try {
            OrderModel::editData(['order_status' => $post['status']], ['id' => $order['id']]);
            if ($post['status'] == 3) {
                $user = UserModel::getOne(['id' => $order['user_id']]);
                $integral = $user['integral'] + $order['order_integral'];
                $integralAdd = $user['integral_add'] + $order['order_integral'];
                UserModel::editData(['integral' => $integral, 'integral_add' => $integralAdd], ['id' => $user['id']]);
                UserIntegralLogModel::addData(['user_id' => $user['id'], 'integral' => $order['order_integral'], 'order_id' => $order['id']]);
                if ($user['level_id'] != 1) {
                    $level = UserLevelModel::getOne([['id', '<>', 1], ['num', '<=', $integralAdd]], [], ['num' => 'DESC']);
                    if ($level) {
                        UserModel::editData(['level_id' => $level['id']], ['id' => $user['id']]);
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->responseError('操作失败');
        }

        return $this->responseSuccess('操作成功');
    }

    public function edit($request, $id)
    {
        $order = OrderModel::getOne(['id' => $id]);
        if (!$order) return $this->responseError('订单不存在');

        return view('Order/order_operate', compact('order'));
    }


    public function update($request, $id)
    {
        $param = $request->param();

        $order = OrderModel::getOne(['id' => $id]);

        if (!$order) return $this->responseError('订单不存在');

        $inputData = [

            'feedback' => $param['content'],
        ];
        try {
            OrderModel::editData($inputData, ['id' => $id]);
        } catch (\Exception $e) {
            return $this->responseError('操作失败');
        }
        return $this->responseSuccess('操作成功');
    }


    public function orderIntegral($request)
    {
        $id = $request->get('id');

        return view('Order/order_integral', compact('id'));
    }


    /**
     * @param $request
     * @return \think\Response
     */
    public function orderIntegralOperate($request)
    {
        $param = $request->param();

        if (empty($param['num'])) return $this->responseError('附近积分不能为空');

        $order = OrderModel::getOne(['id' => $param['order_id']]);

        if (!$order) return $this->responseError('订单不存在');

        Db::startTrans();
        try {
            OrderModel::incValue(['id' => $order['id']], 'add_integral', $param['num']);

            $user = UserModel::getOne(['id' => $order['user_id']]);
            $integral = $user['integral'] + $param['num'];
            $integralAdd = $user['integral_add'] + $param['num'];
            UserModel::editData(['integral' => $integral, 'integral_add' => $integralAdd], ['id' => $user['id']]);
            UserIntegralLogModel::addData(['user_id' => $user['id'], 'integral' => $param['num'], 'order_id' => $order['id']]);
            if ($user['level_id'] != 1) {
                $level = UserLevelModel::getOne([['id', '<>', 1], ['num', '<=', $integralAdd]], [], ['num' => 'DESC']);
                if ($level) {
                    UserModel::editData(['level_id' => $level['id']], ['id' => $user['id']]);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->responseError('操作失败');
        }

        return $this->responseSuccess('操作成功');
    }


    public function export($request)
    {
        $search = $request->get();
        $where = [];
        if (!empty($search['nickname'])) {
            $where[] = ['b.nickname', 'like', "%{$search['nickname']}%"];
        }

        if (!empty($search['name'])) {
            $where[] = ['c.name', 'LIKE', "%{$search['name']}%"];
        }

        empty($search['order_status']) ? $search['order_status'] = '' : $search['order_status'];
        if (!empty($search['order_status'])) {
            $where[] = ['a.order_status', '=', $search['order_status']];
        }
        if ($request->account['project_ids']) {
            $where[] = ['a.project_id', 'in', $request->account['project_ids']];
        }

        $list = Db::table('pro_order')->alias('a')->join('pro_user b', 'a.user_id = b.id')->join('pro_project c', 'c.id = a.project_id')->where($where)->field('a.id,a.order_sn,a.order_integral,a.add_integral,a.client_name,a.client_mobile,a.client_realname,a.client_address,a.create_time,a.order_status,b.nickname,c.name')->order(['a.id' => 'DESC'])->select();

        $tbody = [];
        $thead = ['订单号', '项目', '昵称', '积分', '附加积分', '客户名称', '客户手机号', '联系人', '联系人地址', '下单时间', '订单状态'];
        foreach ($list as $key => $item) {
            $status = '审核中';
            if ($item['order_status'] == 2) {
                $status = '未通过';
            }
            if ($item['order_status'] == 3) {
                $status = '已同意';
            }
            $tbody_tmp = [];
            $tbody_tmp[] = $item['order_sn'];
            $tbody_tmp[] = $item['name'];
            $tbody_tmp[] = $item['nickname'];
            $tbody_tmp[] = $item['order_integral'];
            $tbody_tmp[] = $item['add_integral'];
            $tbody_tmp[] = $item['client_name'];
            $tbody_tmp[] = $item['client_mobile'];
            $tbody_tmp[] = $item['client_realname'];
            $tbody_tmp[] = $item['client_address'];
            $tbody_tmp[] = date('Y-m-d H:i:s', $item['create_time']);
            $tbody_tmp[] = $status;
            $tbody[] = $tbody_tmp;
        }
        // 导出文件
        $filePath = env('runtime_path') . 'order_' . date('Ymd') . '.csv';
        exportCsv($filePath, $thead, $tbody);
    }
}